//
//  MNDOpenDepositoryPaymentViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/14.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import <TTTAttributedLabel.h>
#import "MNDWebViewController.h"
#import "MNDAlertViewController.h"
#import "UIImage+JKColor.h"

@interface MNDOpenDepositoryPaymentViewController () <TTTAttributedLabelDelegate>

@property (weak, nonatomic) IBOutlet UITextField *captchaTextField;
@property (weak, nonatomic) IBOutlet UIButton *sendCaptchaButton;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *protocolLabel;

@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;

@property (nonatomic, copy) NSString *alertMessage;

@end

@implementation MNDOpenDepositoryPaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __block UITextField *captchaField = self.captchaTextField;
    
    [self.captchaTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 4) {
            captchaField.text = [x substringToIndex:4];
        }
    }];
    
    [self loadSignIntroductionMessage];
    
    [self initialBackButton];
    
    [self addAgreementLabelAttribute];
    
    [self loadDepositInfo];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initialRightBarButton {
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
//    [item setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)rightBarButtonAction:(id)sender {
    if (self.alertMessage) {
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        MNDAlertViewController *alertController = [storyboard instantiateViewControllerWithIdentifier:[MNDAlertViewController description]];
        [KeyWindow addSubview:alertController.view];
        [self.tabBarController addChildViewController:alertController];
        
        alertController.alertTitle = @"缴费授权说明";
        alertController.alertMessage = self.alertMessage;
    }
}

- (void)loadSignIntroductionMessage {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_SIGN_INTRODUCTION parameters:[MNDSign signedParamWithDict:@{@"type": @"payment"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.alertMessage = responseModel.data[@"introductions"];
            [weakself initialRightBarButton];
        }
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)loadDepositInfo {
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"1"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                
                weakself.noticeLabel.text = responseModel.msg[@"error"];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            [self backAction:nil];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)grantAction:(UIButton *)sender {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParamWithDict:@{@"channel": @"app"}];
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PAYMENT parameters:param method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        NSLog(@"response: %@", responseModel.data);
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"缴费授权签约";
            webVC.fromNaviIndex = weakself.fromNaviIndex;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
            
        } else {
            [weakself loadDepositInfoWithErrorStr:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        NSLog(@"error: %@", error);
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadDepositInfoWithErrorStr:(NSString *)errorStr {
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                NSString *signStr = responseModel.msg[@"sign"];
                //未完成缴费授权弹出报错信息
                if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
                    [NetworkProgressHUD showHudMsg:errorStr];
                    //已完成缴费授权直接跳到下一步
                } else if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kSignAutoTransfer]) {
                    [weakself loadUserPhoneWithStatus:signStr];
                } else {
                    [NetworkProgressHUD showHudMsg:@"您已开通存管"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakself backAction:nil];
                    });
                }
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } else {
            [NetworkProgressHUD showHudMsg:@"您已开通存管"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself backAction:nil];
            });
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserPhoneWithStatus:(NSString *)depositStatus {
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            if ([depositStatus isEqualToString:kSignAutoTender]) {
                MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
                tenderVC.isResign = NO;
                tenderVC.fromNaviIndex = weakself.fromNaviIndex;
                tenderVC.phoneNumber = responseModel.data;
                    
                [weakself.navigationController pushViewController:tenderVC animated:YES];
            }
            if ([depositStatus isEqualToString:kSignAutoTransfer]) {
                MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
                transferVC.fromNaviIndex = weakself.fromNaviIndex;
                transferVC.phoneNumber = responseModel.data;
                    
                [weakself.navigationController pushViewController:transferVC animated:YES];
            }
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.protocolLabel.highlightedTextColor = kColorDarkOrange;
    //检测类型
    self.protocolLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.protocolLabel.delegate = self;
    //不显示下划线
    self.protocolLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"点击按钮表示您同意《缴费授权协议》";
    [self.protocolLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange = [[mutableAttributedString string] rangeOfString:@"《缴费授权协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange = [text rangeOfString:@"《缴费授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url = [NSURL URLWithString:kPaymentAccord];
    [self.protocolLabel addLinkToURL:url withRange:linkRange];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    
    webVC.title = @"缴费授权协议";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
